package com.ndp.fb.walle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.ndp.ec.core.UserService;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.connectionobject.ConnectionObjectType;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.model.business.vo.connectionobject.result.ConnectionObjectVo;
import com.ndp.fb.rdb.model.ConnectionObject;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.walle.business.AdPublishConditionService;
import com.ndp.fb.walle.business.ConnectionObjectService;
import com.ndp.fb.walle.business.ProductConfigurationService;
import com.ndp.fb.walle.model.bo.connectionobject.ConnObjectProductConfigBo;
import com.ndp.fb.walle.model.bo.connectionobject.ConnectionObjectBo;
import com.ndp.fb.walle.model.bo.productconfiguration.result.ProductConfigurationBo;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.model.vo.connectionobject.param.ConnectionObjectVoParam;
import com.ndp.fb.walle.model.vo.connectionobject.result.ConnectionObjectExtVo;
import com.ndp.fb.walle.util.ConversionUtils;
import com.ndp.fb.walle.util.ResponseUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2014/10/24.
 */
@RequestMapping("/connectionobjects")
@Controller
public class ConnectionObjectController {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * connectionObjectService
     */
    @Autowired
    private ConnectionObjectService connectionObjectService;

    @Autowired
    private AdPublishConditionService adPublishConditionService;

    @Autowired
    private ProductConfigurationService productConfigurationService;

    @Reference
    private UserService userService;

    /**
     *  主要使用在资源管理使用, 图片上传、标签管理
     * 查询当前用户有权限的应用，不受产品管理的开启限制
     */
    @RequestMapping(value = "searchConnectionObjectsByResourceManage")
    @ResponseBody
    public ResponseEntity<String> searchConnectionObjectsByResourceManage(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("ConnectionObjectController searchConnectionObjects() begin.");
        ErrorType errorType = null;
        List<ConnectionObject> data = null;
        try {
            User user = (User) request.getSession().getAttribute("user");
            ConnectionObjectVoParam connectionObjectVoParam = JSON.parseObject(param, ConnectionObjectVoParam.class);

            String userId = user.getTicket();
            List<Long> roleIds = userService.getRoleByUser(user.getId());

            if (ListUtil.isNotEmpty(roleIds) && (roleIds.contains(CommonConstants.ROLE_UIDESIGNER) || roleIds.contains(CommonConstants.ROLE_OUTERUIDESIGNER))) {
                //设计者查询该公司下All有权限的应用
                data = connectionObjectService.findByOrgIdAndType(user.getOrgId(), ConnectionObjectType.Application.getType());
            } else {
                data = connectionObjectService.findByUserIdAndType(userId, connectionObjectVoParam.getTypeId().intValue());
            }

            //Evan 2016/1/6 把当前user对应公司管辖的外链产品追加上
            if (null == data){
                data = new ArrayList<>();
            }
            data.addAll(adPublishConditionService.findOutlinkByOrgId(user.getOrgId()));
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error("", e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        logger.info("ConnectionObjectController searchConnectionObjects() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 主要使用在自定义受众  当前用户 下为owner的应用
     */
    @RequestMapping(value = "searchOwnerConnObj")
    @ResponseBody
    public ResponseEntity<String> searchOwnerConnObj(HttpServletRequest request) {
        logger.info("ConnectionObjectController searchOwnerConnObj() begin.");
        ErrorType errorType = null;
        List<ConnectionObjectVo> data = new ArrayList<>();
        try {
            User user = (User) request.getSession().getAttribute("user");
            String userId = user.getTicket();
            List<ConnectionObject>  resultList = connectionObjectService.findOwnerConnObjByUserId(userId);
            if(ListUtil.isNotEmpty(resultList))
            {
                ConnectionObjectVo vo;
                if(ListUtil.isNotEmpty(resultList))
                {
                    for (ConnectionObject bo : resultList) {
                        vo = new ConnectionObjectVo();
                        ConversionUtils.conversion(bo, vo);
                        data.add(vo);
                    }
                }
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error("ConnectionObjectController searchOwnerConnObj()", e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        logger.info("ConnectionObjectController searchOwnerConnObj() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 用于广告发布搜索应用
     * @param param   param
     * @param request request
     * @return ResponseEntity<String>
     * @author Sisi 创建时间 2014年7月29日 下午2:24:32
     */
    @RequestMapping(value = "searchConnectionObjectsAndConfig")
    @ResponseBody
    public ResponseEntity<String> searchConnectionObjectsAndConfig(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("ConnectionObjectController searchConnectionObjectsAndConfig() begin.");
        ErrorType errorType = null;
        List<ConnectionObjectExtVo> data = null;
        try {
            User user = (User) request.getSession().getAttribute("user");
            ConnectionObjectVoParam connectionObjectVoParam = JSON.parseObject(param, ConnectionObjectVoParam.class);
            List<ConnectionObject> boList;
            if (connectionObjectVoParam != null && StringUtil.isNotEmpty(connectionObjectVoParam.getTypeId() + "") && ConnectionObjectType.Application.getType() == connectionObjectVoParam.getTypeId().intValue()) {
                //查询当前用户产品管理中开启的应用
                boList = adPublishConditionService.findByTypeAndUserId(connectionObjectVoParam.getTypeId().intValue(), user.getTicket());
            } else {
                //这个分支暂时不知有何用
                boList = connectionObjectService.findByUserIdAndType(user.getTicket(), connectionObjectVoParam.getTypeId().intValue());
            }

            if (ListUtil.isNotEmpty(boList)) {
                data = connectionObjectBosToExtVos(boList);
                for (ConnectionObjectExtVo connectionObjectVo : data) {
                    Long fbConnectionObjectId = connectionObjectVo.getFbConnectionObjectId();
                    //查询当前用户产品管理中开启的应用配置
                    List<ProductConfigurationBo> productConfigurationBos = productConfigurationService.findAllProductConfigurationByConnectionObjectId(fbConnectionObjectId, user.getTicket());
                    connectionObjectVo.setProductConfigurations(productConfigurationBos);
                }
            } else {
                data = new ArrayList<>();
            }
            //Evan 2016/1/6 把当前user管辖的外链产品追加上
            data.addAll(adPublishConditionService.findOpenedOutlinkByUserIdAndOrgId(user.getTicket(), user.getOrgId()));
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error("ConnectionObjectController searchConnectionObjectsAndConfig() error:", e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        logger.info("ConnectionObjectController searchConnectionObjectsAndConfig() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    private List<ConnectionObjectExtVo> connectionObjectBosToExtVos(List<ConnectionObject> boList) throws Exception{
        List<ConnectionObjectExtVo> results = new ArrayList<>();
        ConnectionObjectExtVo vo;
        if (ListUtil.isNotEmpty(boList)) {
            for (ConnectionObject bo : boList) {
                vo = new ConnectionObjectExtVo();
                BeanUtils.copyProperties(vo, bo);
                results.add(vo);
            }
        }
        return results;
    }

    /**
     * @param connectionObjectBoList
     * @return
     */
    private List<ConnectionObjectVo> connectionObjectBosToVos(List<ConnectionObjectBo> connectionObjectBoList) {
        List<ConnectionObjectVo> results = new ArrayList<>();
        ConnectionObjectVo vo;
        if (ListUtil.isNotEmpty(connectionObjectBoList)) {
            for (ConnectionObjectBo bo : connectionObjectBoList) {
                vo = new ConnectionObjectVo();
                ConversionUtils.conversion(bo, vo);
                results.add(vo);
            }
        }
        return results;
    }

    /**
     * 投放控制中打开的应用和产品
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "searchAppsAndConfigurations")
    @ResponseBody
    public ResponseEntity<String> searchAppsAndConfigurations(HttpServletRequest httpServletRequest) {
        ErrorType errorType = null;
        List<ConnObjectProductConfigBo> data = new ArrayList<>();
        try {
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            String userId = user.getTicket();
            List<ConnObjectProductConfigBo>  bos = connectionObjectService.searchAppsAndConfigurations(userId);

            //Add  by evan 过滤出来 在投放控制中打开的
            List<ConnectionObject> boList = adPublishConditionService.findByTypeAndUserId(2, userId);
            if (ListUtil.isNotEmpty(boList) && ListUtil.isNotEmpty(bos)) {
                for (ConnObjectProductConfigBo dataBo : bos) {
                    for (ConnectionObject bo : boList) {
                        if (dataBo.getFbConnectionObjectId().equals(bo.getFbConnectionObjectId())) {
                            data.add(dataBo);
                        }
                    }
                }
            }
            //Evan 2016/1/6 把当前user管辖的外链产品追加上
            List<ConnectionObjectExtVo> outLinks = adPublishConditionService.findOpenedOutlinkByUserIdAndOrgId(userId, user.getOrgId());
            data.addAll(transferWithCfgBo(outLinks));
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error("searchAppsAndConfigurations", e);
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 外链结果转化为带配置的产品列表
     */
    private List<ConnObjectProductConfigBo> transferWithCfgBo(List<ConnectionObjectExtVo> outlinks)
    {
        List<ConnObjectProductConfigBo> vos = new ArrayList<>();
        if(ListUtil.isEmpty(outlinks))
            return vos;
        ConnObjectProductConfigBo vo;
        for(ConnectionObjectExtVo connectionObjectExtVo : outlinks)
        {
            vo = new ConnObjectProductConfigBo();
            vo.setFbConnectionObjectId(connectionObjectExtVo.getFbConnectionObjectId());
            vo.setId(connectionObjectExtVo.getId()); //id应该没什么用
            vo.setName(connectionObjectExtVo.getName());
            vo.setProductType(connectionObjectExtVo.getProductType());
            vo.setConfigurations(connectionObjectExtVo.getProductConfigurations());
            vos.add(vo);
        }
        return vos;
    }
    /**
     * 投放控制中打开的应用和产品
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "searchConnectionobjects")
    @ResponseBody
    public ResponseEntity<String> searchConnectionobjects(@RequestParam(value = "param", required = true) String param,HttpServletRequest httpServletRequest) {
        ErrorType errorType = null;
        List<ConnectionObject> data = null;
        try {
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            ConnectionObjectVoParam connectionObjectVoParam = JSON.parseObject(param, ConnectionObjectVoParam.class);
            data = connectionObjectService.findByFbAccountId(connectionObjectVoParam.getFb_account_id());
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error("searchAppsAndConfigurations", e);
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }
}
